import 'reflect-metadata';
import { Request, Response } from 'express';
import { Autowired, Singleton, get, Controller, post } from '../decorator';
import { UserServiceImpl, UserSericeInter } from '../service';
import CollectionInstance from '../collection';
import { getSession } from '../util/sessionUtil';
import { Userinfo } from '../entity/UserInfo';

@Controller('/')
class UserController {
  @Autowired('userServiceImpl') //Autowired 相当于注入：inject ，把外部的对象注入当前装饰器修饰的属性中
  @Singleton(true)
  private userServiceImpl!: UserSericeInter;

  @get('/login')
  login(req: Request, res: Response): void {
    console.log('进入了login');
    let htmlstr = `
      <div>
       <form method="post" action="/loginprocess">
          <div> 用户名： <input type="text" name="username" /></div>
          <div> 密码： <input type="password" name="pwd" /></div>
          <div><input type="submit" value="提交" /></div>
       </form>
      </div>
    `;
    res.send(htmlstr);
  }

  @post('/loginprocess')
  loginprocess(req: Request, res: Response): void {
    console.log('loginprocess=this==', this);
    let session = getSession(req);
    let UserServiceImpl: UserServiceImpl = Reflect.getOwnPropertyDescriptor(
      UserController.prototype,
      'userServiceImpl'
    )?.value;
    let userinfofrmdb: Userinfo | null = UserServiceImpl.Login(
      req.body.username,
      req.body.pwd
    );
    if (userinfofrmdb && userinfofrmdb.username) {
      session.userinfofrmdb = userinfofrmdb;
    }
    res.setHeader('Content-Type', 'text/html;charset=UTF-8');
    let outputhtml = '';
    if (userinfofrmdb && userinfofrmdb.role === 'admin') {
      outputhtml += ` <div>  管理员：${userinfofrmdb.role} </div>`;
      outputhtml += ` <div> <a href="/rights"> 进入管理员权限页面</a> </div>`;
    }
    res.write(outputhtml);
    res.write(`<div>登录成功，欢迎你：${userinfofrmdb?.username}</div>`);
    res.write(`<div><a href="/"> 进入首页</a></div>`);
    res.end();
  }
}

export {};
